﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebAppAuthAdmin.Code;
using Web.Framework;
using AuthApi.Contracts;
using WebAppAuthAdmin.Code.Security;

namespace WebAppAuthAdmin.App
{
    public partial class ContextPicker : BasePage
    {
        public List<Company> CompanyList
        {
            get
            {
                return (List<Company>)ViewState["CompanyList"];
            }
            set
            {
                ViewState["CompanyList"] = value;
            }
        }

        private List<Company> _selectedContextCompanyList = null;
        public List<Company> SelectedContextCompanyList
        {
            get
            {
                if (_selectedContextCompanyList == null)
                {
                    _selectedContextCompanyList = AppContext.Instance.GetCompanyContext(this.Context);
                }

                return _selectedContextCompanyList;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!this.IsPostBack)
                {
                    CompanyList = new List<Company>();
                    CompanyList.Add(CompanyIndependiente.Instance);
                    CompanyList.AddRange(WebServiceHelper.GetCompanyList(string.Empty));

                    List<Company> companiesToRemove = new List<Company>();
                    foreach (var company in CompanyList)
                    {
                        if (company != CompanyIndependiente.Instance)
                        {
                            if (!HasPermissionFor(AppSecurity.APP_VIEW_COMPANY_ID_ + company.Id.ToString()))
                            {
                                companiesToRemove.Add(company);
                            }
                        }
                    }

                    foreach (var company in companiesToRemove)
                    {
                        CompanyList.Remove(company);
                    }

                    Bind();
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ExceptionManager.Instance.GetExceptionMessage(ex), WebMessageType.Error);
            }
        }

        public void ShowMessage(string message, WebMessageType type)
        {
            ShowMessage("Mensaje", message, type);
        }

        public void ShowMessage(string title, string message, WebMessageType type)
        {
            this.pnlMessages.CssClass = "pnlMessagesClass displayBlock";
            this.txtErrorTitle.Text = title;
            this.txtMessages.Text = message;
            if (type != WebMessageType.Error)
            {
                pnlError.CssClass = "errorPanelMessage";
            }
            else
            {
                pnlError.CssClass = "errorPanelError";
            }
        }

        protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    Company company = (Company)e.Row.DataItem;

                    CheckBox chkSelect = (CheckBox)e.Row.Cells[0].FindControl("chkSelectRow");
                    chkSelect.Checked = SelectedContextCompanyList.Where(c => c.Id == company.Id).Count() > 0;
                    if (chkSelect.Checked)
                    {
                        this.hidCheckedRows.Value += string.Format("#{0}#", company.Id);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ExceptionManager.Instance.GetExceptionMessage(ex), WebMessageType.Error);
            }
        }

        protected void Grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void Bind()
        {           
            this.Grid.DataSource = CompanyList;
            this.Grid.DataBind();
        }

        private void Validar()
        {
            // TODO
        }

        private void Save()
        {
            List<int> selectedRowsIds = UIHelper.GetSelectedRowIds(this.hidCheckedRows.Value);

            List<Company> newSelectedCompaniesList = new List<Company>();

            foreach (int selectedId in selectedRowsIds)
            {
                newSelectedCompaniesList.Add(CompanyList.Where(c => c.Id == selectedId).Single());
            }

            AppContext.Instance.SetCompanyContext(this.Context, newSelectedCompaniesList);

            Bind();

            ShowMessage("Se aplicó el contexto", WebMessageType.Notification);
        }

        protected void lnkGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                Validar();
                Save();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}